package ViewModel;

import android.content.Context;
import android.os.LocaleList;
import android.os.Message;
import android.os.Process;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.example.administrator.drinkdevice.AddSelectGoodsActivity;
import com.example.administrator.drinkdevice.MainActivity;
import com.example.administrator.drinkdevice.R;

import org.json.JSONArray;
import org.json.JSONObject;
import org.w3c.dom.Text;

import Component.CustomViewPager;
import Const.PublicDefine;
import DataAccess.DeviceDataAccess;
import DataAccess.OptionDataAccess;
import Device.colaMixing.param_Constant;
import Helper.FlowLayout;
import Interface.IAsynCallBackListener;
import views.Activity_SelectGoods_GoodsInfo;
import views.Dialog_Settlement;
import views.Dialog_TakeCup;
import views.View_GoodsSetting_DeviceInfo;
import views.View_SelectGoods_DeviceInfo;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;


public class SelectGoods_ViewModel extends Base_ViewModel {

    private CustomViewPager viewPager;
    private MainActivity_ViewModel mainViewModel;
    private DeviceDataAccess deviceDataAccess;
    private JSONArray allGoods;
    private JSONObject selectGoods;
    private Activity_SelectGoods_GoodsInfo selectView;
    private Thread getDeviceStateThread;
    public boolean exitflag = false;

    private FlowLayout flowLayout;
    private LinearLayout warning;
    private ScrollView scrollview;
    public ButtonBind busiBtn = new ButtonBind("结算");

    public SelectGoods_ViewModel(Context ctx, CustomViewPager viewPager, MainActivity_ViewModel mainViewModel) {
        super(ctx);
        this.viewPager = viewPager;
        this.mainViewModel = mainViewModel;
        deviceDataAccess = new DeviceDataAccess(ctx);
    }

    public void Init() {
        try {
            busiBtn.Visible.set(GONE);
            flowLayout = ((MainActivity) getBaseContext()).findViewById(R.id.flowLayout);
            warning = ((MainActivity) getBaseContext()).findViewById(R.id.warning);
            scrollview = ((MainActivity) getBaseContext()).findViewById(R.id.scrollview);
            scrollview.setVisibility(VISIBLE);
            warning.setVisibility(GONE);
            //获取所有分级信息
            PublicDefine.colaReader.getAllSlaveDeviceStatus();

            if (mainViewModel.takeCupFlag == 1) {
                mainViewModel.takeCupFlag = 0;
                new Dialog_TakeCup(getBaseContext(), mainViewModel.selectGoods, mainViewModel.checkCup);
            }

            PublicDefine.webService.getBarList(new IAsynCallBackListener() {
                @Override
                public void onFinish(Object sender, Object data) {
                    final String resStr = (String) data;
                    Message msg = new Message();
                    msg.obj = new IAsynCallBackListener() {
                        @Override
                        public void onFinish(Object sender, Object data) {
                            try {
                                JSONObject res = new JSONObject(resStr);
                                if (!res.getBoolean("success")) {
                                    throw new Exception(res.getString("message"));
                                }
                                JSONObject resData = res.getJSONObject("result");
                                JSONArray goodsList = resData.getJSONArray("records");

                                allGoods = new JSONArray();
                                for (int i = 0; i < PublicDefine.colaReader.slave_DeviceInfo.total_device_number; i++) {
                                    String deviceId = PublicDefine.colaReader.slave_DeviceInfo.dev_id[i];
                                    boolean online = (PublicDefine.colaReader.slave_DeviceInfo.Config_Flag[i] & param_Constant.CONFIG_ONLINE_BIT)
                                            == param_Constant.CONFIG_ONLINE_BIT;
                                    if (!online) {
                                        continue;
                                    }

                                    //更新卖品信息
                                    JSONObject deviceInfo = deviceDataAccess.getById(deviceId);
                                    if (deviceInfo != null) {
                                        JSONArray goodsArray = deviceInfo.getJSONArray("goodsList");
                                        for (int j = goodsArray.length() - 1; j >= 0; j--) {
                                            JSONObject goodsInfo = goodsArray.getJSONObject(j);
                                            boolean hasGoods = false;
                                            for (int k = 0; k < goodsList.length(); k++) {
                                                JSONObject goodsJson = goodsList.getJSONObject(k);
                                                if (goodsInfo.getInt("goodsId") == goodsJson.getInt("goodsId")) {
                                                    hasGoods = true;
                                                    JSONObject pickTime = null;
                                                    if (goodsInfo.has("pickTime")) {
                                                        pickTime = goodsInfo.getJSONObject("pickTime");
                                                    }
                                                    goodsInfo = goodsJson;
                                                    if (pickTime != null){
                                                        goodsInfo.put("pickTime", pickTime);
                                                    }
                                                    goodsArray.put(j, goodsInfo);
                                                    break;
                                                }
                                            }
                                            if (!hasGoods) {
                                                goodsArray.remove(j);
                                            }
                                        }
                                        deviceInfo.put("goodsList", goodsArray);
                                        deviceDataAccess.setDevice(deviceInfo);

                                        for (int j = goodsArray.length() - 1; j >= 0; j--) {
                                            JSONObject goodsInfo = goodsArray.getJSONObject(j);
                                            goodsInfo.put("deviceId", deviceId);
                                            if (!goodsInfo.has("pickTime")) {
                                                continue;
                                            }

                                            allGoods.put(goodsInfo);
                                        }
                                    }
                                }

                                setGoodsViews();

                            } catch (Exception e) {
                                e.printStackTrace();
                                alert(GetExceptionMsg(e));
                            }
                        }

                        @Override
                        public void onError(Object sender, Exception e) {

                        }
                    };
                    mHandler.sendMessage(msg);
                }

                @Override
                public void onError(Object sender, Exception e) {
                    e.printStackTrace();
                    alert(GetExceptionMsg(e));
                }
            });

            exitflag = false;
            getDeviceStateThread = new Thread(runnableUi);
            getDeviceStateThread.start();

        } catch (Exception e) {
            e.printStackTrace();
            alert(GetExceptionMsg(e));
        }
    }

    private void setGoodsViews() throws Exception {
        flowLayout.removeAllViews();
        if (allGoods.length() == 0){
            scrollview.setVisibility(GONE);
            warning.setVisibility(VISIBLE);
        }
        for (int i = 0; i < allGoods.length(); i++) {
            JSONObject goodsInfo = allGoods.getJSONObject(i);
            Activity_SelectGoods_GoodsInfo goodsView = new Activity_SelectGoods_GoodsInfo(getBaseContext(), goodsInfo, new IAsynCallBackListener() {
                @Override
                public void onFinish(Object sender, Object data) {
                    selectView = (Activity_SelectGoods_GoodsInfo) sender;
                    selectGoods = (JSONObject) data;
                    setSelectView();
                }

                @Override
                public void onError(Object sender, Exception e) {

                }
            });
            flowLayout.addView(goodsView);
        }
    }

    public void setSelectView() {
        if (flowLayout == null) {
            return;
        }

        for (int i = 0; i < flowLayout.getChildCount(); i++) {
            Activity_SelectGoods_GoodsInfo goodsView = (Activity_SelectGoods_GoodsInfo) flowLayout.getChildAt(i);
            if (goodsView == selectView) {
                busiBtn.Visible.set(VISIBLE);
                goodsView.setCheck(true);
            } else if ((boolean) goodsView.getTag()) {
                goodsView.setCheck(false);
            }
        }
    }

    long lastClickTime = 0;
    long MIN_CLICK_DELAY_TIME = 2000;
    public void settlementClick(View view) {
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
            // 超过点击间隔后再将lastClickTime重置为当前点击时间
            lastClickTime = curClickTime;
        } else {
            return;
        }

        try {
            //获取设备信息
            PublicDefine.webService.getDeviceInfo(new IAsynCallBackListener() {
                @Override
                public void onFinish(Object sender, Object data) {
                    String resStr = (String) data;
                    try {
                        JSONObject res = new JSONObject(resStr);
                        if (!res.getBoolean("success")) {
                            throw new Exception(res.getString("message"));
                        }

                        final int storageId = res.getJSONObject("result").getInt("storageId");

                        //获取货位列表
                        PublicDefine.webService.getGoodsLocationList(storageId, new IAsynCallBackListener() {
                            @Override
                            public void onFinish(Object sender, Object data) {
                                String resStr = (String) data;
                                try {
                                    JSONObject res = new JSONObject(resStr);
                                    if (!res.getBoolean("success")) {
                                        throw new Exception(res.getString("message"));
                                    }

                                    JSONArray locations = res.getJSONObject("result").getJSONObject("return_data").getJSONArray("pageData");
                                    if (locations.length() == 0) {
                                        throw new Exception("未绑定货位");
                                    }

                                    JSONObject location = locations.getJSONObject(0);

                                    JSONObject goods = new JSONObject();
                                    goods.put("goodsId", selectGoods.getInt("goodsId"));
                                    goods.put("amount", 1);
                                    JSONArray goodsList = new JSONArray();
                                    goodsList.put(goods);

                                    //检查库存
                                    PublicDefine.webService.checkGoodsStock(storageId, location.getInt("id"), goodsList, new IAsynCallBackListener() {
                                        @Override
                                        public void onFinish(Object sender, Object data) {
                                            final String resStr = (String) data;
                                            Message msg = new Message();
                                            msg.obj = new IAsynCallBackListener() {
                                                @Override
                                                public void onFinish(Object sender, Object data) {
                                                    try {
                                                        JSONObject res = new JSONObject(resStr);
                                                        if (!res.getBoolean("success")) {
                                                            throw new Exception(res.getString("message"));
                                                        }

                                                        new Dialog_Settlement(getBaseContext(), selectGoods, new IAsynCallBackListener() {
                                                            @Override
                                                            public void onFinish(Object sender, Object data) {
                                                                mainViewModel.checkCup = (int) data;
                                                                mainViewModel.selectGoods = selectGoods;
                                                                viewPager.setCurrentItem(11);
                                                            }

                                                            @Override
                                                            public void onError(Object sender, Exception e) {

                                                            }
                                                        });
                                                    } catch (Exception e) {
                                                        e.printStackTrace();
                                                        alert(GetExceptionMsg(e));
                                                    }
                                                }

                                                @Override
                                                public void onError(Object sender, Exception e) {

                                                }
                                            };
                                            mHandler.sendMessage(msg);
                                        }

                                        @Override
                                        public void onError(Object sender, Exception e) {
                                            e.printStackTrace();
                                            alert(GetExceptionMsg(e));
                                        }
                                    });

                                } catch (Exception e) {
                                    e.printStackTrace();
                                    alert(GetExceptionMsg(e));
                                }
                            }

                            @Override
                            public void onError(Object sender, Exception e) {
                                e.printStackTrace();
                                alert(GetExceptionMsg(e));
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                        alert(GetExceptionMsg(e));
                    }
                }

                @Override
                public void onError(Object sender, Exception e) {
                    e.printStackTrace();
                    alert(GetExceptionMsg(e));
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            alert(GetExceptionMsg(e));
        }
    }

    //获取设备状态
    Runnable runnableUi = new Runnable() {
        @Override
        public void run() {
            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
            int round = 30;
            while (!exitflag) {
                try {
                    PublicDefine.colaReader.getMixingDeviceStatus();
                    if (PublicDefine.colaReader.deviceStatus_SettingState != 0){
                        exitflag = true;
                        Message msg = new Message();
                        msg.obj = new IAsynCallBackListener() {
                            @Override
                            public void onFinish(Object sender, Object data) {
                                viewPager.setCurrentItem(1);
                            }

                            @Override
                            public void onError(Object sender, Exception e) {

                            }
                        };
                        mHandler.sendMessage(msg);
                    }
                    Thread.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                    alert(e.getMessage());
                }
            }
        }
    };
}
